package cn.itsource.hrm.handler;

import cn.itsource.hrm.config.RabbitmqConfig;
import cn.itsource.hrm.constants.MQConstants;
import cn.itsource.hrm.feignclients.FastdfsFeignClient;
import cn.itsource.hrm.util.MyFileUtils;
import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.util.Map;

@Component
public class PageStaticHandler {

    @Autowired
    private FastdfsFeignClient fastdfsFeignClient;
    //监听email队列
    @RabbitListener(queues = {MQConstants.NAME_QUEUE_PAGE_DIRECT})
    public void receive_email(String msg, Message message, Channel channel) throws IOException {
        //解析获取的消息
        Map<String,String> mqMessage = JSON.parseObject(msg, Map.class);
        //下载地址
        String htmlPathInFastdfs = mqMessage.get("htmlPathInFastdfs");
        //nginx物理路径
        String physicalPath = mqMessage.get("physicalPath");

        //从fastdfs下载html
        //把byte[] 下载到磁盘
        byte[] htmlBytes = fastdfsFeignClient.download(htmlPathInFastdfs);

        if(htmlBytes!=null && htmlBytes.length>0){
            //创建文件
            File file = MyFileUtils.createFile(physicalPath);
            //把html拷贝到nginx的物理路径
            FileCopyUtils.copy(htmlBytes,file);
            //触发手动签收
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
